/*
 * @(#)PublishController.java 1.0 2019年1月4日上午10:29:51
 *
 * 
 * Copyright (c) , Inc. All rights reserved.
 */
package com.saturn.config.server.web;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.saturn.config.server.base.dto.ConfigInfo;
import com.saturn.config.server.base.dto.JsonResult;
import com.saturn.config.server.service.ConfigLogService;
import com.saturn.config.server.util.HttpUtil;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <dl>
 *    <dt><b>Title:</b></dt>
 *    <dd>
 *    	none
 *    </dd>
 *    <dt><b>Description:</b></dt>
 *    <dd>
 *    	<p>none
 *    </dd>
 * </dl>
 *
 * @author tanks
 * @version 1.0, 2019年1月4日
 * @since JdbcConfigServer
 * 
 */
@Slf4j
@RestController
public class PublishController {
	
	@Autowired
	private ConfigLogService logInfoService;
	@Autowired
	private EurekaClient eurekaClient;
	
	@CrossOrigin
	@RequestMapping(value = "/notifyRefresh", produces = "application/json")
	public JsonResult notifyRefresh(HttpServletRequest request) {
		JsonResult jsonResult = new JsonResult();
		List<ConfigInfo> configInfos = logInfoService.queryBroadcastConfigInfos();
		if( configInfos==null || configInfos.size()==0 ) {
			jsonResult.setRespResult(Boolean.FALSE.booleanValue());
			jsonResult.setRespMsg("无变更消息，无需推送刷新通知");
			return jsonResult;
		}
		Set<String> appNames = new HashSet<String>();
		for(ConfigInfo info: configInfos) {
			appNames.add(info.getAppName().toLowerCase());
		}
		//增加应用配置的属性
		List<ConfigInfo> configs = logInfoService.queryCastApplicationName();
		if( configs!=null && configs.size()>0 ){
			for(ConfigInfo config: configs) {
				appNames.add(config.getConfigValue());
			}
		}
		List<Application> applications = eurekaClient.getApplications().getRegisteredApplications();
		if( applications!=null && applications.size()>0 ) {
			boolean send = Boolean.FALSE.booleanValue();
			for(Application app:applications) {
				if( appNames.contains(app.getName().toLowerCase()) && app.getInstances().size()>0) {
					send = Boolean.TRUE.booleanValue();
					List<InstanceInfo> instanceInfos = app.getInstances();
					if( instanceInfos==null || instanceInfos.size()==0 ) continue;
					for(InstanceInfo info:instanceInfos) {
						//bus-refresh BUS总线刷新
						//final String url = "http://" + info.getHostName() + ":" + info.getPort() + "/actuator/bus-refresh?destination=" + info.getAppName()+":" + info.getPort();
						//单节点刷新
						final String url = "http://" + info.getHostName() + ":" + info.getPort() + "/actuator/refresh";
						Thread thread = new Thread() {
							public void run() {
								log.info("调用刷新接口：" + url);
								String result = HttpUtil.sendPost(url, StrUtil.EMPTY);
								log.info("调用刷新结果：" + result);
							}
						};
						thread.start();
					}
				}
			}
			if( !send ) {
				jsonResult.setRespMsg("无匹配的应用，不发送广播更新");
				log.info("无匹配的应用，不发送广播更新");
			}else {
				jsonResult.setRespResult(Boolean.TRUE.booleanValue());
				jsonResult.setRespMsg("刷新成功");
				log.info("配置中心无服务，无法广播通知更新");
			}
			logInfoService.updateCast();
		}else {
			jsonResult.setRespMsg("配置中心无服务，无法广播通知更新");
			log.info("配置中心无服务，无法广播通知更新");
		}
		return jsonResult;
	}
	
}
